//
//  CardGameViewController.m
//  MemoPocker
//
//  Created by Jose Luis Ferreyra on 17/02/13.
//  Copyright (c) 2013 Dharma. All rights reserved.
//

#import "CardGameViewController.h"
#import "PlayingCardDeck.h"
#import "CardMatchingGame.h"
#import "Card.h"
#import "GameResult.h"

@interface CardGameViewController ()
@property (strong, nonatomic) CardMatchingGame *game;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons;
@property (weak, nonatomic) IBOutlet UILabel *scoreLabel;
@property (strong, nonatomic) GameResult *result;
@property (nonatomic) int flipCount;
@end

// test

@implementation CardGameViewController

- (CardMatchingGame *)game {
    if (!_game){
        _game= [[CardMatchingGame alloc] initWithCardCount: self.cardButtons.count
                                                 usingDeck:[[PlayingCardDeck alloc] init]];
    }
    return _game;
}

- (GameResult *) result
{
    if (!_result) _result = [[GameResult alloc] init];
    return _result;
}




- (void)setCardButtons: (NSArray *)cardButtons
{
    _cardButtons=cardButtons;
    [self updateUI];
}

- (void)updateUI{
    
    for (int i=0; i< [self.cardButtons count];i++)
    {
        UIButton *cardButton = [self.cardButtons objectAtIndex:i];
        Card *card = [self.game cardAtIndex:i];
        [cardButton setTitle: card.contents
                    forState:UIControlStateSelected];
        [cardButton setTitle: card.contents
                    forState:UIControlStateSelected|UIControlStateDisabled];
        cardButton.selected = card.isFaceUp;
        cardButton.enabled = !card.isUnplayable;
        cardButton.alpha = (card.isUnplayable) ? 0.3 : 1.0;
    }
    self.scoreLabel.text = [NSString stringWithFormat: @"SCORE: %d", self.game.score];
}

- (IBAction)flipcard:(UIButton *)sender
{
    [self.game flipCardAtIndex: [self.cardButtons indexOfObject: sender]];
    [self updateUI];
    self.result.score = self.game.score;
}

- (IBAction)gameOver {
    self.game = Nil;
    self.result = Nil;
    self.flipCount = 0;
}

@end
